/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.client.model.component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;

/**
 * Used to parse applet code.
 *
 * As the applet code
 * might change in the future, this class encapsulates the
 * changes, as far as parsing is concerned.
 * 
 * @author Walter Lütgenau
 */
public class ComponentEditorParser {
    String html;
    public static final String PAR_CODE = "code";
    protected static final String PARAMETER_START = "n_addApplet(";
    protected static final String PARAMETER_END = ");";

    /**
     * Initialize the applet parser with the HTML string.
     * 
     * @param html
     */
    public ComponentEditorParser(String html) {
        this.html = html;
    }

    /**
     * Return the information about the applet
     * in a data object.
     * 
     * @return the info
     * @throws IOException
     */
    public AppletInfo getAppletInfo() throws IOException {
        if (!isEditorPage())
            return null;
        
        HashMap<String, String> parameters = getParameters();
        String name = parameters.get(PAR_CODE);
        if (name == null)
            return null;

        parameters.remove(PAR_CODE);

        return new AppletInfo(name, parameters);
    }
    
    /**
     * Is this an editor page with a single applet?
     * 
     * @return the result of the check
     */
    protected boolean isEditorPage() {
        if (html.indexOf(PARAMETER_START) < 0 ||
                html.indexOf(PARAMETER_START) != html.lastIndexOf(PARAMETER_START))
            return false;
        return true;
    }

    /**
     * Parse the applet HTML.
     *
     * Build a hashmap of the applet parameters and return it.
     *
     * @return the applet parameters
     * @throws IOException
     */
    protected HashMap<String, String> getParameters() throws IOException {
        BufferedReader reader = new BufferedReader(new StringReader(html));

        String line = null;
        HashMap<String, String> parameters = new HashMap<String, String>();
        boolean parsingParameters = false;
        while ((line = reader.readLine()) != null) {
            if (!parsingParameters && line.indexOf(PARAMETER_START) >= 0) {
                parsingParameters = true;
                continue;
            }

            if (parsingParameters) {
                if (line.indexOf(PARAMETER_END) >= 0)
                    break;
                
                addParameter(parameters, line);
            }
        }
        
        return parameters;
    }

    /**
     * Add a single parameter to the hashmap, that is, key and value.
     * Both key and value will be delimited by comma.
     *
     * @param parameters
     * @param line
     */
    protected void addParameter(HashMap<String, String> parameters, String line) {
        String[] parameter = line.split(",");

        parameters.put(extractValue(parameter[0]), extractValue(parameter[1]));
    }

    /**
     * Trim leading and trailing space as well as leading and trailing hyphens.
     * 
     * @param input
     * @return
     */
    protected String extractValue(String input) {
        return input.trim().replaceAll("'", "");
    }
}
